package org.jeecg.modules.handler;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.config.mqtoken.UserTokenContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.IManageBaseAPI;
import org.jeecg.modules.manage.entity.CaishuiTaskSettle;
import org.jeecg.modules.settle.service.ICaishuiTaskSettleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * @Description: 代发批次与明细查询job
 * @Author: yfkj
 * @Date:   2023-03-05
 * @Version: V1.0
 */
@Component
@Slf4j
public class BatchAndDetailsJobHandler {

    @Resource
    private ICaishuiTaskSettleService iCaishuiTaskSettleService;
    //注入feign客户端
    @Resource
    private IManageBaseAPI iManageBaseAPI;
    @Autowired
    private RedisUtil redisUtil;

    @XxlJob(value = "queryBatchAndDetailsJob")
    public ReturnT<String> queryBatchAndDetailsJobHandler(String params) {
//        log.info("===代发批次与明细查询job===：" + params);
        //1.设置线程会话Token
        UserTokenContext.setToken(getTemporaryToken());
        try {
            //查询所有已通过、发放中的任务结算列表
            QueryWrapper<CaishuiTaskSettle> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(CaishuiTaskSettle::getOrderNo);
            queryWrapper.lambda().eq(CaishuiTaskSettle::getStatus,2);
            queryWrapper.lambda().eq(CaishuiTaskSettle::getExtendStatus,1);
            List<CaishuiTaskSettle> taskSettleList = iCaishuiTaskSettleService.list(queryWrapper);
            if(oConvertUtils.listIsNotEmpty(taskSettleList)){
                for (CaishuiTaskSettle taskSettle : taskSettleList) {
                    //批次与明细查询
                    iManageBaseAPI.handleTaskSettle(taskSettle.getOrderNo());
                }
            }

            //2.使用完删除Token，避免性能
            UserTokenContext.remove();
            return ReturnT.SUCCESS;
        }catch (Exception e){
            log.info(e.getMessage());
            return ReturnT.FAIL;
        }
    }

    /**
     * 获取临时令牌
     * 模拟登陆接口，获取模拟 Token
     * @return
     */
    public static String getTemporaryToken() {
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
        //模拟登录生成临时Token（必须数据库正常用户）
        String username = "loginAccount";
        //参数说明：第一个参数是用户名、第二个参数是密码的加密串
        String token = JwtUtil.sign(username, "??");
        // 设置Token缓存有效时间为 5 分钟
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + username, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + username, 5 * 60 * 1000);
        return token;
    }

}
